package com.study.springcloud.nacos.api;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.study.springcloud.nacos.SpringCloudNacosApiApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author xl-9527
 * @since 2025/7/20
 **/
public class NacosApiDemo {

    private static final Logger log = LoggerFactory.getLogger(SpringCloudNacosApiApplication.class);
    private final NamingService namingService = NamingFactory.createNamingService("127.0.0.1:8848");
    private final String serviceName = "spring-cloud-nacos-api-study";

    public NacosApiDemo() throws NacosException {
    }

    public void discover() throws NacosException {
        final List<Instance> allInstances = namingService.getAllInstances(serviceName);
        for (final Instance allInstance : allInstances) {
            log.info("收到的服务实例：{}", allInstance);
        }
    }

    public void register() throws NacosException {
        namingService.registerInstance(
                serviceName,
                this.getInstance("127.0.0.1", 8080)
        );
    }

    private Instance getInstance(final String ip, final Integer port) {
        final Instance instance = new Instance();
        instance.setIp(ip);
        instance.setPort(port);
        return instance;
    }
}
